package com.basic.modules.ykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.TypeReference;
import com.basic.common.utils.ParamsModel;
import com.basic.common.utils.ParamUtils;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.ykf.entity.YkfCustomerConsultEntity;
import com.basic.modules.ykf.model.CustomerConsultationRecordExcel;
import com.basic.modules.ykf.model.ExcelReq;
import com.basic.modules.ykf.model.SubAccountItem;
import com.basic.modules.ykf.model.WorkOvertimeRecordExcel;
import com.basic.modules.ykf.utils.ExcelCellWidthStyleStrategy;
import com.basic.modules.ykf.utils.ExcelStyleUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.PageUtils;
import com.basic.common.utils.Query;

import com.basic.modules.ykf.dao.YkfWorkOvertimeRecordDao;
import com.basic.modules.ykf.entity.YkfWorkOvertimeRecordEntity;
import com.basic.modules.ykf.service.YkfWorkOvertimeRecordService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service("ykfWorkOvertimeRecordService")
public class YkfWorkOvertimeRecordServiceImpl extends ServiceImpl<YkfWorkOvertimeRecordDao, YkfWorkOvertimeRecordEntity> implements YkfWorkOvertimeRecordService {

    @Autowired
    private SysUserService userService;

    @Override
    public PageUtils queryPage(ParamsModel<YkfWorkOvertimeRecordEntity> params) {
        if (ObjectUtil.isEmpty(params.getSort()) || StrUtil.isBlank(params.getSort().getSidx()) || StrUtil.isBlank(params.getSort().getOrder())) {
            ParamsModel.SortParams sortParams = new ParamsModel.SortParams();
            sortParams.setSidx("createTime");
            sortParams.setOrder("desc");
            params.setSort(sortParams);
        }
        QueryWrapper<YkfWorkOvertimeRecordEntity> queryWrapper = ParamUtils.createQueryWrapperByDefaultSort(params);
        if (ObjectUtil.isNotEmpty(params.getCondition())) {
            if (StrUtil.isNotBlank(params.getCondition().getKeyword())) {
                String keyword = params.getCondition().getKeyword();
                queryWrapper.lambda().and(wrapper -> wrapper.like(YkfWorkOvertimeRecordEntity::getWorkOvertimeNo, keyword)
                        .or().like(YkfWorkOvertimeRecordEntity::getName, keyword)
                        .or().like(YkfWorkOvertimeRecordEntity::getFlowerName, keyword)
                );
            }
            if (ObjectUtil.isNotEmpty(params.getCondition().getDateS())) {
                queryWrapper.lambda().and(wrapper -> wrapper.ge(YkfWorkOvertimeRecordEntity::getStartDate, params.getCondition().getDateS())
                        .or().ge(YkfWorkOvertimeRecordEntity::getEndDate, params.getCondition().getDateS()));
            }
            if (ObjectUtil.isNotEmpty(params.getCondition().getDateE())) {
                queryWrapper.lambda().and(wrapper -> wrapper.le(YkfWorkOvertimeRecordEntity::getStartDate, params.getCondition().getDateE())
                        .or().le(YkfWorkOvertimeRecordEntity::getEndDate, params.getCondition().getDateE()));
            }
        }
        List<Long> powerUIds = userService.getPowerUIds();
        if (ObjectUtil.isEmpty(powerUIds)) {
            return new PageUtils();
        } else {
            if (!powerUIds.contains(0L)) {
                queryWrapper.lambda().in(YkfWorkOvertimeRecordEntity::getUserId, powerUIds);
            }
        }
        IPage<YkfWorkOvertimeRecordEntity> page = this.page(
                new Query<YkfWorkOvertimeRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage())),
                queryWrapper
        );
        if (ObjectUtil.isNotEmpty(page) && ObjectUtil.isNotEmpty(page.getRecords())) {
            for (YkfWorkOvertimeRecordEntity record : page.getRecords()) {
                if (StrUtil.isNotBlank(record.getSubAccountInfo())) {
                    try {
                        Gson gson = new Gson();
                        List<SubAccountItem> list = gson.fromJson(record.getSubAccountInfo(), new TypeToken<List<SubAccountItem>>() {
                        }.getType());
                        record.setSubAccountItemList(list);
                        record.setSubAccountName(list.stream().map(SubAccountItem::getSubAccountName).collect(Collectors.joining(",")));
                    } catch (Exception e) {
                        log.error("解析失败");
                    }
                }
            }
        }
        return new PageUtils(page);
    }

    @Override
    public void overtimeRegistration(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        //查询列表
        ParamsModel<YkfWorkOvertimeRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfWorkOvertimeRecordEntity>() {}));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = queryPage(params);
        List<YkfWorkOvertimeRecordEntity> workList = (List<YkfWorkOvertimeRecordEntity>) pageUtils.getList();
        List<WorkOvertimeRecordExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(workList)) {
            for (YkfWorkOvertimeRecordEntity record : workList) {
                if (StrUtil.isNotBlank(record.getSubAccountInfo())) {
                    try {
                        Gson gson = new Gson();
                        List<SubAccountItem> list1 = gson.fromJson(record.getSubAccountInfo(), new TypeToken<List<SubAccountItem>>() {
                        }.getType());
                        record.setSubAccountItemList(list1);
                        record.setSubAccountName(list1.stream().map(SubAccountItem::getSubAccountName).collect(Collectors.joining(",")));
                    } catch (Exception e) {
                        log.error("解析失败");
                    }
                }
                WorkOvertimeRecordExcel excel = new WorkOvertimeRecordExcel();
                BeanUtil.copyProperties(record, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("加班登记记录", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), WorkOvertimeRecordExcel.class)
                .sheet("加班登记记录")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

}
